import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '../views/layout/layout'
Vue.use(VueRouter)  

const routes = [
  {
    path:'/',
    redirect: '/layout'
  },
  {
    path: '/layout',
    name: 'layout',
    component: layout,
    meta: {
      needLogin: true,
    },
    children: [
      {
        path: '/layout',
        redirect: "/layout/home", 
      },
      {
        path:'/layout/home',
        component: () => import(/* webpackChunkName: "about" */ '../views/home/home.vue'),
        children: [
          {
            path: '/layout/home',
            redirect: "/layout/home/item1", 
          },
          {
            path:'item1',
            component: () => import(/* webpackChunkName: "about" */ '../views/home/pages/item1.vue'),
          },
          {
            path:'item2',
            component: () => import(/* webpackChunkName: "about" */ '../views/home/pages/item2.vue'),
          },
          {
            path:'item3',
            component: () => import(/* webpackChunkName: "about" */ '../views/home/pages/item3.vue'),
          }
        ]
      },
      {
        path:'/layout/list',
        component: () => import(/* webpackChunkName: "about" */ '../views/list/list.vue')
      }
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "about" */ '../views/login/login.vue')
  },
  {
    path: '/detail/:id/:tag',
    name: 'detail',
    meta: {
      needLogin: true,
    },
    component: () => import(/* webpackChunkName: "about" */ '../views/detail/detail.vue')
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]
const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next) => {
  if(to.meta.needLogin) {
    if(window.sessionStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
